package com.atguigu.wc.transform;

import com.atguigu.wc.beans.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoMapFunction;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

/**
 * @Author:GaoFei
 * @Description:
 * @Date:Created in 18:11
 * @Modified By:
 */
public class SplitTransform4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> stringDataStreamSource = env.readTextFile("D:\\1BIGDATA\\spark-streaming\\Flink\\src\\main\\resources\\hello.txt");
        SplitStream<SensorReading> splitStreamDataSource = stringDataStreamSource
                .map(line -> {
                    String[] split = line.split(",");
                    return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
                })
                .split(out -> out.getTemperature() > 30 ? Collections.singletonList("high") : Collections.singletonList("low"));
        DataStream<SensorReading> highTemperature = splitStreamDataSource.select("high");
        DataStream<SensorReading> lowTemperature = splitStreamDataSource.select("low");
        DataStream<SensorReading> allTemperature = splitStreamDataSource.select("high","low");
        highTemperature.print("high");
        // 二流合并
        SingleOutputStreamOperator<Tuple2<String, Double>> map = highTemperature
                .map(new MapFunction<SensorReading, Tuple2<String, Double>>() {

                    @Override
                    public Tuple2<String, Double> map(SensorReading value) throws Exception {
                        return new Tuple2<>(value.getId(), value.getTemperature());
                    }
                });
        ConnectedStreams<Tuple2<String, Double>, SensorReading> connect = map.connect(lowTemperature);
        SingleOutputStreamOperator<Object> resultDataStream = connect.map(new CoMapFunction<Tuple2<String, Double>, SensorReading, Object>() {
            @Override
            public Object map1(Tuple2<String, Double> stringDoubleTuple2) throws Exception {
                return new Tuple3<>(stringDoubleTuple2.f0, stringDoubleTuple2.f1, "high temp warning");
            }

            @Override
            public Object map2(SensorReading sensorReading) throws Exception {
                return new Tuple2<>(sensorReading.getId(), "normal");
            }
        });
        resultDataStream.print();
        env.execute();

    }
}
